<template>
  <div class="location">
    <div class="search">
      <van-field
        v-model.trim="keyword"
        placeholder="搜索"
        @input="handleChange"
      />
    </div>
    <div class="list">
      <div
        class="item"
        v-for="(item, index) in list"
        :key="index"
        @click="handleItemClick(item)"
      >
        {{ item.name }}
      </div>
    </div>

    <div class="map">
      <div class="title">当前位置:</div>
      <div id="map-container"></div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      keyword: "",
      list: [],
    };
  },
  methods: {
    // 搜索框内容变化监听
    handleChange() {
      var that = this;
      AMap.plugin("AMap.Autocomplete", function () {
        // 实例化Autocomplete
        var autoOptions = {
          //city 限定城市，默认全国
          city: "全国",
        };
        var autoComplete = new AMap.Autocomplete(autoOptions);
        autoComplete.search(that.keyword, function (status, result) {
          // 搜索成功时，result即是对应的匹配数据
          that.list = result.tips;
        });
      });
    },
    // 列表点击
    handleItemClick(item) {
      // 保存到vuex
      this.$store.commit("setlocationAddress", item);
      // 跳转到首页
      this.$router.push("/home");
    },
  },
  mounted() {
    if (this.$store.state.locationAddress.name) {
      var map = new AMap.Map("map-container", {
        resizeEnable: true,
        center: [
          this.$store.state.locationAddress.location.lng,
          this.$store.state.locationAddress.location.lat,
        ],
        zoom: 15,
      });

      var marker = new AMap.Marker({
        position: [
          this.$store.state.locationAddress.location.lng,
          this.$store.state.locationAddress.location.lat,
        ],
      });
      map.add(marker); //添加到地图
    } else {
      new AMap.Map("map-container");
    }
  },
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
